namespace SimpleWebServices.Configuration
{
    using System;
    using System.Configuration;
    using System.Diagnostics.CodeAnalysis;
    using System.Xml;
    using System.Xml.Serialization;

    [XmlRoot("redirection")]
    public sealed class RedirectionConfiguration : IConfigurationSectionHandler
    {
        public RedirectionConfiguration()
        {
            this.Domains = new RedirectionCollection();
            this.Paths = new RedirectionCollection();
            this.Uri = new RedirectionCollection();
        }

        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Can't deserialize if the setter is private.")]
        [XmlElement("domains")]
        public RedirectionCollection Domains
        {
            get;
            set;
        }

        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Can't deserialize if the setter is private.")]
        [XmlElement("paths")]
        public RedirectionCollection Paths
        {
            get;
            set;
        }

        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Can't deserialize if the setter is private.")]
        [XmlElement("uri")]
        public RedirectionCollection Uri
        {
            get;
            set;
        }

        public static RedirectionConfiguration Settings()
        {
            return RedirectionConfiguration.Settings("simplewebservices/redirection");
        }

        public static RedirectionConfiguration Settings(string sectionName)
        {
            RedirectionConfiguration result = ConfigurationManager.GetSection(sectionName) as RedirectionConfiguration;

            return result ?? new RedirectionConfiguration();
        }

        public object Create(object parent, object configContext, XmlNode section)
        {
            RedirectionConfiguration result = null;

            if (section != null)
            {
                try
                {
                    result = section.OuterXml.Deserialize<RedirectionConfiguration>();
                }
                catch (Exception exception)
                {
                    throw new ConfigurationErrorsException(exception.Message, exception, section);
                }
            }

            return result ?? new RedirectionConfiguration();
        }
    }
}